package com.example.basic.configinfo;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import androidx.annotation.Nullable;

import com.example.basic.logs.Logger;
import com.example.basic.security.encrypt.MD5Util;
import com.example.basic.utils.ApplicationContextUtils;

import java.util.Iterator;
import java.util.List;

public class APKInfo {

    private static final String TAG = "APKInfo";

    private static String mAppVersionName;
    private static int mAppVersionCode;
    private static String mBuildFlavor;

    public static void initApkInfo(Context context, String flavor) {
        mBuildFlavor = flavor;
        initPackageVersion(context);
        DeviceInfo.init(context);
    }

    private static void initPackageVersion(Context context) {
        mAppVersionName = "";
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo packageInfo = pm.getPackageInfo(context.getApplicationContext().getPackageName(), 0);
            if (packageInfo != null) {
                mAppVersionName = packageInfo.versionName;
                mAppVersionCode = packageInfo.versionCode;
            }
        } catch (PackageManager.NameNotFoundException e) {
            // Do nothing, versionCode stays -1
        }
    }

    public static String getApkInfoStr() {
        return "版本号：" + mAppVersionName + "\n" +
                "版本号：" + mAppVersionCode + "\n" +
                "APK渠道：" + mBuildFlavor + "\n" +
                "签名文件MD5值：" + getSignMd5Str(ApplicationContextUtils.getApplicationContext());
    }



    /**
     * 获取app签名md5值,与  keytool -list -v -keystore xxxx.keystore -storepass 签名文件密码 获取的md5值一样
     */
    @Nullable
    public static String getSignMd5Str(Context context) {
        PackageManager pm = context.getPackageManager();
        List<PackageInfo> apps = pm.getInstalledPackages(PackageManager.GET_SIGNATURES);
        Iterator<PackageInfo> iter = apps.iterator();
        while(iter.hasNext()) {
            PackageInfo packageinfo = iter.next();
            String packageName = packageinfo.packageName;
            if (packageName.equals(context.getPackageName())) {
                Logger.d(TAG, "getSign: " + packageinfo.signatures[0].toCharsString());
                return MD5Util.encryptionMD5(packageinfo.signatures[0].toByteArray());
            }
        }
        return null;
    }



}
